<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/index.css">
    <script src="js/jquery-1.12.4.min.js"></script>
    <script src="js/template-native.js"></script>
    <!-- 创建模板 -->
    <script type="text/html" id="tem">
        <% for (var i = 0; i < comments.length; i++) { %>
            <li uid="<%= comments[i].id %>">
                <p class="floor"><%= comments[i].id %>楼<a href="javascript:;" class="delete">删除</a></p>
                <p class="author">层主： <span class="name"><%= comments[i].username %></span></p>
                <p class="content"><%= comments[i].content %></p>
            </li>
        <% } %>
    </script>
</head>

<body>
    <div class="main">
        <div class="post">
            <h2>主题：畅所欲言</h2>
            <p class="author">楼主： 二三</p>
            <p class="txt">以此启程，永远有远方可以奔赴</p>
        </div>
        <div class="reply">
            <h4>发表留言</h4>
            <p>昵称： <input type="text" class="user"></p>
            <textarea class="editor"></textarea>
            <input type="button" value="发表" class="btn">
        </div>
        <div class="cmts">
            <ul class="list">

            </ul>
        </div>
    </div>
    <script>
        //  获取数据
        var $list = $(".cmts .list")
        var $btn = $(".reply .btn")
        var $user = $(".reply .user")
        var $editor = $(".reply .editor")

        // 获取后台数据
        $.ajax({
            url: "http://localhost:3000/db",
            type: "GET",
            success: function (data) {
                // console.log(data)
                $list.html(template("tem", data));
                deleteData()
            }
        })

        // 添加点击事件 向数据库中添加新的数据
        $btn.click(function () {
            var username = $user.val();
            var content = $editor.val();
            $.ajax({
                url: " http://localhost:3000/comments",
                type: "POST",
                dataType: "json",
                data: { username: username, content: content },
                success: function (data) {
                    // console.log(data)
                    $list.append(template("tem", { "comments": [data] }))
                    deleteData()
                }
            })
            $user.val("");
            $editor.val("");
        })

        // 点击删除 删除留言
        function deleteData() {
            $(".cmts .list .delete").click(function () {
                $li = $(this).parents("li");
                var index = $li.attr("uid");
                $.ajax({
                    url: " http://localhost:3000/comments/" + index,
                    type: "DELETE"
                })
                $li.remove();
            })
        }
    </script>
</body>

</html>